package cn.thoughtworks.school.pactise.diary.adapters.inbound.rest.resources.comment;

import cn.thoughtworks.school.pactise.diary.adapters.inbound.rest.auth.annotation.Auth;
import cn.thoughtworks.school.pactise.diary.adapters.inbound.rest.auth.configrations.AuthResolver;
import cn.thoughtworks.school.pactise.diary.application.usecases.comment.EditCommentUseCase;
import cn.thoughtworks.school.pactise.diary.domain.context.practiseDiaryContext.comment.Comment;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping(value = "/api/comments")
public class CommentResource {
    private final EditCommentUseCase editCommentUseCase;

    public CommentResource(EditCommentUseCase editCommentUseCase) {
        this.editCommentUseCase = editCommentUseCase;
    }

    @RequestMapping(value = "", method = RequestMethod.POST)
    public ResponseEntity<CreateCommentDto> createComment(@RequestBody CommentRequest commentRequest,
                                                          @Auth AuthResolver.User user) {
        Date now = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        commentRequest.setCommentAuthorId(user.getId());
        commentRequest.setCommentTime(simpleDateFormat.format(now));
        Comment comment = editCommentUseCase.save(commentRequest.toDomain());

        return new ResponseEntity(new CreateCommentDto("/api/users/" + user.getId() + "/comments/" + comment.getId()), HttpStatus.CREATED);
    }
}
